home *** CD-ROM | disk | FTP | other *** search
/ Freelog 22 / freelog 22.iso / Prog / Djgpp / GPC2952B.ZIP / lib / gcc-lib / djgpp / 2.952 / units / gpc.pas < prev    next >
Encoding:
Pascal/Delphi Source File  |  2001-02-08  |  79.9 KB  |  1,674 lines

  1. {
  2. Pascal declarations of the GPC Run Time System that are visible to
  3. each program.
  4.  
  5. This unit contains Pascal declarations of many RTS routines which
  6. are not built into the compiler and can be called from programs.
  7. Don't copy the declarations from this unit into your programs, but
  8. rather include this unit with a `uses' statement. The reason is that
  9. the internal declarations, e.g. the `asmnames', may change, and this
  10. unit will be changed accordingly. @@In the future, this unit might
  11. be included into every program automatically, so there will be no
  12. need for a `uses' statement to make the declarations here available.
  13.  
  14. Note about `protected var' parameters:
  15. Since const parameters in GPC may be passed by value *or* by
  16. reference internally, possibly depending on the system, `const foo*'
  17. parameters to C functions *cannot* reliably declared as `const' in
  18. Pascal. However, Extended Pascal's `protected var' can be used since
  19. this guarantees passing by reference.
  20.  
  21. Copyright (C) 1998-2001 Free Software Foundation, Inc.
  22.  
  23. Author: Frank Heckenbach <frank@pascal.gnu.de>
  24.  
  25. This file is part of GNU Pascal.
  26.  
  27. GNU Pascal is free software; you can redistribute it and/or modify
  28. it under the terms of the GNU General Public License as published by
  29. the Free Software Foundation; either version 2, or (at your option)
  30. any later version.
  31.  
  32. GNU Pascal is distributed in the hope that it will be useful,
  33. but WITHOUT ANY WARRANTY; without even the implied warranty of
  34. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  35. GNU General Public License for more details.
  36.  
  37. You should have received a copy of the GNU General Public License
  38. along with GNU Pascal; see the file COPYING. If not, write to the
  39. Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
  40. 02111-1307, USA.
  41.  
  42. As a special exception, if you link this file with files compiled
  43. with a GNU compiler to produce an executable, this does not cause
  44. the resulting executable to be covered by the GNU General Public
  45. License. This exception does not however invalidate any other
  46. reasons why the executable file might be covered by the GNU General
  47. Public License.
  48. }
  49.  
  50. {$gnu-pascal,B-,I-}
  51.  
  52. module GPC interface;
  53.  
  54. export
  55.   GPC = all;
  56.   GPC_SP = (eread (*@@not really, but an empty export doesn't work*));
  57.   GPC_EP = (eread (*@@not really, but an empty export doesn't work*));
  58.   GPC_BP = (MaxLongInt, ExitCode, ErrorAddr, Pos);
  59.   GPC_Delphi = (MaxLongInt, Int64, EConvertError, ExitCode,
  60.                 ErrorAddr, Pos, SetString, StringOfChar, TextFile,
  61.                 AssignFile, CloseFile);
  62.  
  63. const
  64.   MaxLongInt = High (LongInt);
  65.  
  66.   { Maximum size of a variable }
  67.   MaxVarSize = MaxInt div 8;
  68.  
  69. type
  70.   Int64 = Integer (64);
  71.  
  72. { ====================== MEMORY MANAGEMENT ======================= }
  73.  
  74. { Heap manipulation, from heap.c }
  75.  
  76. { GPC implements both Mark/Release and Dispose. Both can be mixed freely
  77.   in the same program. Dispose should be preferred, since it's faster. }
  78.  
  79. { C heap management routines. NOTE: if Release is used anywhere in
  80.   the program, CFreeMem and CReAllocMem may not be used for pointers
  81.   that were not allocated with CGetMem. }
  82. function  CGetMem     (Size : SizeType) : Pointer;                        asmname 'malloc';
  83. procedure CFreeMem    (aPointer : Pointer);                               asmname 'free';
  84. function  CReAllocMem (aPointer : Pointer; NewSize : SizeType) : Pointer; asmname 'realloc';
  85.  
  86. type
  87.   GetMemType     = ^function (Size : SizeType) : Pointer;
  88.   FreeMemType    = ^procedure (aPointer : Pointer);
  89.   ReAllocMemType = ^function (aPointer : Pointer; NewSize : SizeType) : Pointer;
  90.  
  91. { These variables can be set to user-defined routines for memory
  92.   allocation/deallocation. GetMemPtr may return nil when
  93.   insufficient memory is available. GetMem/New will produce a
  94.   runtime error then. }
  95. var
  96.   GetMemPtr     : GetMemType; asmname '_p_getmem_ptr'; external;
  97.   FreeMemPtr    : FreeMemType; asmname '_p_freemem_ptr'; external;
  98.   ReAllocMemPtr : ReAllocMemType; asmname '_p_reallocmem_ptr'; external;
  99.  
  100.   { Points to the lowest byte of heap used }
  101.   HeapBegin : Pointer; asmname '_p_heap_begin'; external;
  102.  
  103.   { Points to the highest byte of heap used }
  104.   HeapHigh  : Pointer; asmname '_p_heap_high'; external;
  105.  
  106. const
  107.   UndocumentedReturnNil = Pointer (- 1);
  108.  
  109. { Returns the number of pointers that would be released. aPointer must
  110.   have been marked with Mark. For an example of its usage, see the
  111.   HeapMon unit. }
  112. function  ReleaseCount (aPointer : Pointer) : Integer; asmname '_p_releasecount';
  113.  
  114. procedure ReAllocMem (var aPointer : Pointer; NewSize : SizeType); asmname '_p_reallocmem';
  115.  
  116. { Routines to handle endianness, from endian.pas }
  117.  
  118. { Boolean constants about endianness and alignment }
  119.  
  120. const
  121.   BitsBigEndian  = {$ifdef __BITS_LITTLE_ENDIAN__} False
  122.                    {$else}{$ifdef __BITS_BIG_ENDIAN__} True
  123.                    {$else}{$error Bit endianness is not defined!}
  124.                    {$endif}{$endif};
  125.  
  126.   BytesBigEndian = {$ifdef __BYTES_LITTLE_ENDIAN__} False
  127.                    {$else}{$ifdef __BYTES_BIG_ENDIAN__} True
  128.                    {$else}{$error Byte endianness is not defined!}
  129.                    {$endif}{$endif};
  130.  
  131.   WordsBigEndian = {$ifdef __WORDS_LITTLE_ENDIAN__} False
  132.                    {$else}{$ifdef __WORDS_BIG_ENDIAN__} True
  133.                    {$else}{$error Word endianness is not defined!}
  134.                    {$endif}{$endif};
  135.  
  136.   NeedAlignment  = {$ifdef __NEED_ALIGNMENT__} True
  137.                    {$else} False {$endif};
  138.  
  139. { Convert single variables from or to little or big endian format.
  140.   This only works for a single variable or a plain array of a simple
  141.   type. For more complicated structures, this has to be done for
  142.   each component separately! Currently, ConvertFromFooEndian and
  143.   ConvertToFooEndian are the same, but this might not be the case on
  144.   middle-endian machines. Therefore, we provide different names. }
  145. procedure ReverseBytes            (var Buf; ElementSize, Count : SizeType); asmname '_p_reversebytes';
  146. procedure ConvertFromLittleEndian (var Buf; ElementSize, Count : SizeType); asmname '_p_convertlittleendian';
  147. procedure ConvertFromBigEndian    (var Buf; ElementSize, Count : SizeType); asmname '_p_convertbigendian';
  148. procedure ConvertToLittleEndian   (var Buf; ElementSize, Count : SizeType); asmname '_p_convertlittleendian';
  149. procedure ConvertToBigEndian      (var Buf; ElementSize, Count : SizeType); asmname '_p_convertbigendian';
  150.  
  151. { Read a block from a file and convert it from little or
  152.   big endian format. This only works for a single variable or a
  153.   plain array of a simple type, note the comment for
  154.   `ConvertFromLittleEndian' and `ConvertFromBigEndian'. }
  155. (*@@iocritical*)procedure BlockReadLittleEndian   (var aFile : File; var   Buf; ElementSize, Count : SizeType); asmname '_p_blockread_littleendian';
  156. (*@@iocritical*)procedure BlockReadBigEndian      (var aFile : File; var   Buf; ElementSize, Count : SizeType); asmname '_p_blockread_bigendian';
  157.  
  158. { Write a block variable to a file and convert it to little or big
  159.   endian format before. This only works for a single variable or a
  160.   plain array of a simple type. Apart from this, note the comment
  161.   for `ConvertToLittleEndian' and `ConvertToBigEndian'. }
  162. (*@@iocritical*)procedure BlockWriteLittleEndian  (var aFile : File; const Buf; ElementSize, Count : SizeType); asmname '_p_blockwrite_littleendian';
  163. (*@@iocritical*)procedure BlockWriteBigEndian     (var aFile : File; const Buf; ElementSize, Count : SizeType); asmname '_p_blockwrite_bigendian';
  164.  
  165. { Read and write strings from/to binary files, where the length is
  166.   stored in the given endianness and with a fixed size (64 bits),
  167.   and therefore is independent of the system. }
  168. (*@@iocritical*)procedure ReadStringLittleEndian  (var f : File; var s : String);   asmname '_p_ReadStringLittleEndian';
  169. (*@@iocritical*)procedure ReadStringBigEndian     (var f : File; var s : String);   asmname '_p_ReadStringBigEndian';
  170. (*@@iocritical*)procedure WriteStringLittleEndian (var f : File; const s : String); asmname '_p_WriteStringLittleEndian';
  171. (*@@iocritical*)procedure WriteStringBigEndian    (var f : File; const s : String); asmname '_p_WriteStringBigEndian';
  172.  
  173. { =================== STRING HANDLING ROUTINES =================== }
  174.  
  175. { String handling routines, from string.pas }
  176.  
  177. type
  178.   AnyFile = Text; (*@@ create `AnyFile' parameters*)
  179.   PAnyFile = ^AnyFile;
  180.  
  181. { TString is a string type that is used for function results and
  182.   local variables, as long as undiscriminated strings are not
  183.   allowed there. The default size of 2048 characters should be
  184.   enough for file names on any system, but can be changed when
  185.   necessary. It should be at least as big as MAXPATHLEN. }
  186.  
  187. const
  188.   TStringSize = 2048;
  189.   SpaceCharacters = [' ', #9];
  190.   NewLine = "\n"; { the separator of lines within a string }
  191.   LineBreak = {$ifdef __OS_DOS__} "\r\n" {$else} "\n" {$endif}; { the separator of lines within a file }
  192.  
  193. type
  194.   TString    = String (TStringSize);
  195.   TStringBuf = packed array [0 .. TStringSize] of Char;
  196.   PString    = ^String;
  197.   CharSet    = set of Char;
  198.   PCStrings  = ^TCStrings;
  199.   TCStrings  = array [0 .. MaxVarSize div SizeOf (CString)] of CString;
  200.  
  201. var
  202.   CParamCount : Integer; asmname '_p_argc'; external;
  203.   CParameters : PCStrings; asmname '_p_argv'; external;
  204.  
  205. function  MemCmp      (const s1, s2; Size : SizeType) : Integer; asmname 'memcmp';
  206. function  MemComp     (const s1, s2; Size : SizeType) : Integer; asmname 'memcmp';
  207. function  MemCompCase (const s1, s2; Size : SizeType) : Boolean; asmname '_p_memcmpcase';
  208.  
  209. procedure UpCaseString    (var s : String);                                      asmname '_p_upcase_string';
  210. procedure LoCaseString    (var s : String);                                      asmname '_p_locase_string';
  211. function  UpCaseStr       (const s : String) : TString;                          asmname '_p_upcase_str';
  212. function  LoCaseStr       (const s : String) : TString;                          asmname '_p_locase_str';
  213.  
  214. function  IsUpCase        (ch : Char) : Boolean;                                 attribute (const); asmname '_p_isupcase';
  215. function  IsLoCase        (ch : Char) : Boolean;                                 attribute (const); asmname '_p_islocase';
  216. function  IsAlpha         (ch : Char) : Boolean;                                 attribute (const); asmname '_p_isalpha';
  217. function  IsAlphaNum      (ch : Char) : Boolean;                                 attribute (const); asmname '_p_isalphanum';
  218. function  IsAlphaNumUnderscore (ch : Char) : Boolean;                            attribute (const); asmname '_p_isalphanumunderscore';
  219. function  IsSpace         (ch : Char) : Boolean;                                 attribute (const); asmname '_p_isspace';
  220. function  IsPrintable     (ch : Char) : Boolean;                                 attribute (const); asmname '_p_isprintable';
  221.  
  222. function  StrEqualCase    (const s1, s2 : String) : Boolean;                     asmname '_p_strequalcase';
  223.  
  224. function  Pos             (const SubString, aString : String) : Integer;             asmname '_p_pos';
  225. function  LastPos         (const SubString, aString : String) : Integer;             asmname '_p_lastpos';
  226. function  PosCase         (const SubString, aString : String) : Integer;             asmname '_p_poscase';
  227. function  LastPosCase     (const SubString, aString : String) : Integer;             asmname '_p_lastposcase';
  228. function  CharPos         (const Chars : CharSet; const aString : String) : Integer; asmname '_p_charpos';
  229. function  LastCharPos     (const Chars : CharSet; const aString : String) : Integer; asmname '_p_lastcharpos';
  230.  
  231. function  PosFrom         (const SubString, aString : String; From : Integer) : Integer;             asmname '_p_posfrom';
  232. function  LastPosTill     (const SubString, aString : String; Till : Integer) : Integer;             asmname '_p_lastpostill';
  233. function  PosFromCase     (const SubString, aString : String; From : Integer) : Integer;             asmname '_p_posfromcase';
  234. function  LastPosTillCase (const SubString, aString : String; Till : Integer) : Integer;             asmname '_p_lastpostillcase';
  235. function  CharPosFrom     (const Chars : CharSet; const aString : String; From : Integer) : Integer; asmname '_p_charposfrom';
  236. function  LastCharPosTill (const Chars : CharSet; const aString : String; Till : Integer) : Integer; asmname '_p_lastcharpostill';
  237.  
  238. function  IsPrefix        (const Prefix, s : String) : Boolean;                     asmname '_p_isprefix';
  239. function  IsSuffix        (const Suffix, s : String) : Boolean;                     asmname '_p_issuffix';
  240. function  IsPrefixCase    (const Prefix, s : String) : Boolean;                     asmname '_p_isprefixcase';
  241. function  IsSuffixCase    (const Suffix, s : String) : Boolean;                     asmname '_p_issuffixcase';
  242.  
  243. function  CStringLength      (Src : CString) : SizeType;                            asmname '_p_strlen';
  244. function  CStringEnd         (Src : CString) : CString;                             asmname '_p_strend';
  245. function  CStringNew         (Src : CString) : CString;                             asmname '_p_strdup';
  246. function  CStringComp        (s1, s2 : CString) : Integer;                          asmname '_p_strcmp';
  247. function  CStringCaseComp    (s1, s2 : CString) : Integer;                          asmname '_p_strcasecmp';
  248. function  CStringLComp       (s1, s2 : CString; MaxLen : SizeType) : Integer;       asmname '_p_strlcmp';
  249. function  CStringLCaseComp   (s1, s2 : CString; MaxLen : SizeType) : Integer;       asmname '_p_strlcasecmp';
  250. function  CStringCopy        (Dest, Source : CString) : CString;                    asmname '_p_strcpy';
  251. function  CStringCopyEnd     (Dest, Source : CString) : CString;                    asmname '_p_strecpy';
  252. function  CStringLCopy       (Dest, Source : CString; MaxLen : SizeType) : CString; asmname '_p_strlcpy';
  253. function  CStringMove        (Dest, Source : CString; Count : SizeType) : CString;  asmname '_p_strmove';
  254. function  CStringCat         (Dest, Source : CString) : CString;                    asmname '_p_strcat';
  255. function  CStringLCat        (Dest, Source : CString; MaxLen : SizeType) : CString; asmname '_p_strlcat';
  256. function  CStringChPos       (Src : CString; Ch : Char) : CString;                  asmname '_p_strscan';
  257. function  CStringLastChPos   (Src : CString; Ch : Char) : CString;                  asmname '_p_strrscan';
  258. function  CStringPos         (aString, SubString : CString) : CString;              asmname '_p_strpos';
  259. function  CStringLastPos     (aString, SubString : CString) : CString;              asmname '_p_strrpos';
  260. function  CStringCasePos     (aString, SubString : CString) : CString;              asmname '_p_strcasepos';
  261. function  CStringLastCasePos (aString, SubString : CString) : CString;              asmname '_p_strrcasepos';
  262. function  CStringUpCase      (s : CString) : CString;                               asmname '_p_strupper';
  263. function  CStringLoCase      (s : CString) : CString;                               asmname '_p_strlower';
  264. function  CStringIsEmpty     (s : CString) : Boolean;                               asmname '_p_strempty';
  265. function  NewCString         (const Source : String) : CString;                     asmname '_p_newcstring';
  266. function  CStringCopyString  (Dest : CString; const Source : String) : CString;     asmname '_p_cstringcopystring';
  267. procedure CopyCString        (Source : CString; var Dest : String);                 asmname '_p_copycstring';
  268.  
  269. function  NewString       (const s : String) : PString;                          asmname '_p_newstring';
  270. procedure DisposeString   (p : PString);                                         asmname '_p_dispose';
  271.  
  272. procedure SetString       (var s : String; Buffer : PChar; Count : Integer);     asmname '_p_set_string';
  273. function  StringOfChar    (Ch : Char; Count : Integer) = s : TString;            asmname '_p_string_of_char';
  274.  
  275. procedure TrimLeft        (var s : String);                                      asmname '_p_trimleft';
  276. procedure TrimRight       (var s : String);                                      asmname '_p_trimright';
  277. procedure TrimBoth        (var s : String);                                      asmname '_p_trimboth';
  278. function  TrimLeftStr     (const s : String) : TString;                          asmname '_p_trimleft_str';
  279. function  TrimRightStr    (const s : String) : TString;                          asmname '_p_trimright_str';
  280. function  TrimBothStr     (const s : String) : TString;                          asmname '_p_trimboth_str';
  281.  
  282. function  GetStringCapacity (const s : String) : Integer;                        asmname '_p_get_string_capacity';
  283.  
  284. { A shortcut for a common use of WriteStr as a function }
  285. function  Integer2String (i : Integer) : TString;                                asmname '_p_Integer2String';
  286.  
  287. type
  288.   TChars = packed array [1 .. 1] of Char;
  289.   PChars = ^TChars;
  290.  
  291.   { Under development. Interface subject to change.
  292.     Use with caution. }
  293.   { When a const or var AnyString parameter is passed, internally
  294.     these records are passed as const parameters. Value AnyString
  295.     parameters are passed like value string parameters. }
  296.   ConstAnyString = record
  297.     Length : Integer;
  298.     Chars  : PChars
  299.   end;
  300.  
  301.   { Capacity is the allocated space (used internally). Count is the
  302.     actual number of environment strings. The CStrings array
  303.     contains the environment strings, terminated by a nil pointer,
  304.     which is not counted in Count. @CStrings can be passed to libc
  305.     routines like execve which expect an environment (see
  306.     GetCEnvironment). }
  307.   PEnvironment = ^TEnvironment;
  308.   TEnvironment (Capacity : Integer) = record
  309.     Count : Integer;
  310.     CStrings : array [1 .. Capacity + 1] of CString
  311.   end;
  312.  
  313. var
  314.   Environment : PEnvironment; asmname '_p_environment'; external;
  315.  
  316. { Get an environment variable. If it does not exist, GetEnv returns
  317.   the empty string, which can't be distinguished from a variable
  318.   with an empty value, while CStringGetEnv returns nil then. Note,
  319.   Dos doesn't know empty environment variables, but treats them as
  320.   non-existing, and does not distinguish case in the names of
  321.   environment variables. However, even under Dos, empty environment
  322.   variables and variable names with different case can now be set
  323.   and used within GPC programs. }
  324. function  GetEnv (const EnvVar : String) : TString;                        asmname '_p_getenv';
  325. function  CStringGetEnv (EnvVar : CString) : CString;                      asmname '_p_cstringgetenv';
  326.  
  327. { Sets an environment variable with the name given in VarName to the value
  328.   Value. A previous value, if any, is overwritten. }
  329. procedure SetEnv (const VarName, Value : String);                          asmname '_p_setenv';
  330.  
  331. { Un-sets an environment variable with the name given in VarName. }
  332. procedure UnSetEnv (const VarName : String);                               asmname '_p_unsetenv';
  333.  
  334. { Returns @Environment^.CStrings, converted to PCStrings, to be passed to
  335.   libc routines like execve which expect an environment. }
  336. function  GetCEnvironment : PCStrings;                                     asmname '_p_getcenvironment';
  337.  
  338. { ================= RUNTIME ERROR HANDLING ETC. ================== }
  339.  
  340. { Error handling functions, from error.pas }
  341.  
  342. const
  343.   EOpen = 405;
  344.   EOpenRead = 442;
  345.   EOpenWrite = 443;
  346.   EOpenUpdate = 444;
  347.   EReading = 464;
  348.   EWriting = 466;
  349.   ERead = 413;
  350.   EWrite = 414;
  351.   EWriteReadOnly = 422;
  352.   EMMap = 408;
  353.   EIOCtl = 630;
  354.   EConvertError = 875;
  355.  
  356. var
  357.   { Error number (after runtime error) or exit status (after Halt) or
  358.     0 (during program run and after succesful termination). }
  359.   ExitCode : Integer; asmname '_p_exitcode'; external;
  360.  
  361.   { Contains the address of the code where a runtime occurred, nil
  362.     if no runtime error occurred. }
  363.   ErrorAddr : Pointer; asmname '_p_erroraddr'; external;
  364.  
  365.   { Error message }
  366.   ErrorMessageString : TString; asmname '_p_errormessagestring'; external;
  367.  
  368. function  GetErrorMessage                 (n : Integer) : CString;                   asmname '_p_errmsg';
  369. procedure RuntimeError                    (n : Integer);                             attribute (noreturn); asmname '_p_error';
  370. procedure RuntimeErrorInteger             (n : Integer; i : MedInt);                 attribute (noreturn); asmname '_p_error_integer';
  371. procedure RuntimeErrorCString             (n : Integer; s : CString);                attribute (noreturn); asmname '_p_error_string';
  372. procedure InternalError                   (n : Integer);                             attribute (noreturn); asmname '_p_internal_error';
  373. procedure InternalErrorInteger            (n : Integer; i : MedInt);                 attribute (noreturn); asmname '_p_internal_error_integer';
  374. procedure RuntimeWarning                  (Message : CString);                       asmname '_p_warning';
  375. procedure RuntimeWarningInteger           (Message : CString; i : MedInt);           asmname '_p_warning_integer';
  376. procedure RuntimeWarningCString           (Message : CString; s : CString);          asmname '_p_warning_string';
  377. procedure DebugStatement                  (const FileName : String; Line : Integer); asmname '_p_debug_statement';
  378.  
  379. (*iocritical*)procedure IOError                         (n : Integer);                             asmname '_p_io_error';
  380. (*iocritical*)procedure IOErrorInteger                  (n : Integer; i : MedInt);                 asmname '_p_io_error_integer';
  381. (*iocritical*)procedure IOErrorCString                  (n : Integer; s : CString);                asmname '_p_io_error_string';
  382. (*iocritical*)procedure IOErrorFile                     (n : Integer; protected var f : AnyFile);  asmname '_p_io_error_file';
  383. function  GetIOErrorMessage : TString;                                               asmname '_p_get_io_error_message';
  384. procedure CheckInOutRes;                                                             asmname '_p_check_inoutres';
  385.  
  386. { Registers a procedure to be called to restore the terminal for
  387.   another process that accesses the terminal, or back for the
  388.   program itself. Used e.g. by the CRT unit. The procedures must
  389.   allow for being called multiple times in any order, even at the
  390.   end of the program (see the comment for RestoreTerminal). }
  391. procedure RegisterRestoreTerminal (ForAnotherProcess : Boolean; procedure Proc); asmname '_p_RegisterRestoreTerminal';
  392.  
  393. { Unregisters a procedure registered with RegisterRestoreTerminal.
  394.   Returns False if the procedure had not been registered, and True
  395.   if it had been registered and was unregistered successfully. }
  396. function UnregisterRestoreTerminal (ForAnotherProcess : Boolean; procedure Proc) : Boolean; asmname '_p_UnregisterRestoreTerminal';
  397.  
  398. { Calls the procedures registered by RegisterRestoreTerminal. When
  399.   restoring the terminal for another process, the procedures are
  400.   called in the opposite order of registration. When restoring back
  401.   for the program, they are called in the order of registration.
  402.  
  403.   `RestoreTerminal (True)' will also be called at the end of the
  404.   program, before outputting any runtime error message. It can also
  405.   be used if you want to write an error message and exit the program
  406.   (especially when using e.g. the CRT unit). For this purpose, to
  407.   avoid side effects, call RestoreTerminal immediately before
  408.   writing the error message (to StdErr, not to Output!), and then
  409.   exit the program (e.g. with Halt). }
  410. procedure RestoreTerminal (ForAnotherProcess : Boolean); asmname '_p_RestoreTerminal';
  411.  
  412. { Executes a command line. Reports execution errors via the IOResult
  413.   mechanism and returns the exit status of the executed program.
  414.   Execute calls RestoreTerminal with the argument True before and
  415.   False after executing the process, ExecuteNoTerminal does not. }
  416. (*@@IO critical*)function  Execute (const CmdLine : String) : Integer; asmname '_p_execute';
  417. (*@@IO critical*)function  ExecuteNoTerminal (const CmdLine : String) : Integer; asmname '_p_executenoterminal';
  418.  
  419. procedure AtExit (procedure Proc); asmname '_p_atexit';
  420.  
  421. procedure SetReturnAddress (Address : Pointer);                                      asmname '_p_SetReturnAddress';
  422. procedure RestoreReturnAddress;                                                      asmname '_p_RestoreReturnAddress';
  423.  
  424. { ==================== SIGNALS AND PROCESSES ===================== }
  425.  
  426. function  ProcessID : Integer; asmname '_p_pid';
  427.  
  428. { Extract information from the status returned by PWait }
  429. function StatusExited     (Status : Integer) : Boolean; attribute (const); asmname '_p_WIfExited';
  430. function StatusExitCode   (Status : Integer) : Integer; attribute (const); asmname '_p_WExitStatus';
  431. function StatusSignaled   (Status : Integer) : Boolean; attribute (const); asmname '_p_WIfSignaled';
  432. function StatusTermSignal (Status : Integer) : Integer; attribute (const); asmname '_p_WTermSig';
  433. function StatusStopped    (Status : Integer) : Boolean; attribute (const); asmname '_p_WIfStopped';
  434. function StatusStopSignal (Status : Integer) : Integer; attribute (const); asmname '_p_WStopSig';
  435.  
  436. type
  437.   TSignalHandler = procedure (Signal : Integer);
  438.  
  439. { OldHandler and OldRestart may be null }
  440. function InstallSignalHandler (Signal : Integer; Handler : TSignalHandler;
  441.                                Restart, UnlessIgnored : Boolean;
  442.                                var OldHandler : TSignalHandler; var OldRestart : Boolean) : Boolean; asmname '_p_sigaction';
  443. procedure BlockSignal   (Signal : Integer; Block : Boolean); asmname '_p_BlockSignal';
  444. function  SignalBlocked (Signal : Integer) : Boolean;        asmname '_p_SignalBlocked';
  445.  
  446. var
  447.   { Signal actions }
  448.   SignalDefault : TSignalHandler; asmname '_p_SIG_DFL'; external;
  449.   SignalIgnore  : TSignalHandler; asmname '_p_SIG_IGN'; external;
  450.   SignalError   : TSignalHandler; asmname '_p_SIG_ERR'; external;
  451.  
  452.   { Signals. The constants are set to the signal numbers, and
  453.     are 0 for signals not defined. }
  454.   { POSIX signals }
  455.   SigHUp    : Integer; asmname '_p_SIGHUP'; external;
  456.   SigInt    : Integer; asmname '_p_SIGINT'; external;
  457.   SigQuit   : Integer; asmname '_p_SIGQUIT'; external;
  458.   SigIll    : Integer; asmname '_p_SIGILL'; external;
  459.   SigAbrt   : Integer; asmname '_p_SIGABRT'; external;
  460.   SigFPE    : Integer; asmname '_p_SIGFPE'; external;
  461.   SigKill   : Integer; asmname '_p_SIGKILL'; external;
  462.   SigSegV   : Integer; asmname '_p_SIGSEGV'; external;
  463.   SigPipe   : Integer; asmname '_p_SIGPIPE'; external;
  464.   SigAlrm   : Integer; asmname '_p_SIGALRM'; external;
  465.   SigTerm   : Integer; asmname '_p_SIGTERM'; external;
  466.   SigUsr1   : Integer; asmname '_p_SIGUSR1'; external;
  467.   SigUsr2   : Integer; asmname '_p_SIGUSR2'; external;
  468.   SigChld   : Integer; asmname '_p_SIGCHLD'; external;
  469.   SigCont   : Integer; asmname '_p_SIGCONT'; external;
  470.   SigStop   : Integer; asmname '_p_SIGSTOP'; external;
  471.   SigTStp   : Integer; asmname '_p_SIGTSTP'; external;
  472.   SigTTIn   : Integer; asmname '_p_SIGTTIN'; external;
  473.   SigTTOu   : Integer; asmname '_p_SIGTTOU'; external;
  474.  
  475.   { Non-POSIX signals }
  476.   SigTrap   : Integer; asmname '_p_SIGTRAP'; external;
  477.   SigIOT    : Integer; asmname '_p_SIGIOT'; external;
  478.   SigEMT    : Integer; asmname '_p_SIGEMT'; external;
  479.   SigBus    : Integer; asmname '_p_SIGBUS'; external;
  480.   SigSys    : Integer; asmname '_p_SIGSYS'; external;
  481.   SigStkFlt : Integer; asmname '_p_SIGSTKFLT'; external;
  482.   SigUrg    : Integer; asmname '_p_SIGURG'; external;
  483.   SigIO     : Integer; asmname '_p_SIGIO'; external;
  484.   SigPoll   : Integer; asmname '_p_SIGPOLL'; external;
  485.   SigXCPU   : Integer; asmname '_p_SIGXCPU'; external;
  486.   SigXFSz   : Integer; asmname '_p_SIGXFSZ'; external;
  487.   SigVTAlrm : Integer; asmname '_p_SIGVTALRM'; external;
  488.   SigProf   : Integer; asmname '_p_SIGPROF'; external;
  489.   SigPwr    : Integer; asmname '_p_SIGPWR'; external;
  490.   SigInfo   : Integer; asmname '_p_SIGINFO'; external;
  491.   SigLost   : Integer; asmname '_p_SIGLOST'; external;
  492.   SigWinCh  : Integer; asmname '_p_SIGWINCH'; external;
  493.  
  494.   { Signal subcodes (only used on some systems, -1 if not used) }
  495.   FPEIntegerOverflow        : Integer; asmname '_p_FPE_INTOVF_TRAP'; external;
  496.   FPEIntegerDivisionByZero  : Integer; asmname '_p_FPE_INTDIV_TRAP'; external;
  497.   FPESubscriptRange         : Integer; asmname '_p_FPE_SUBRNG_TRAP'; external;
  498.   FPERealOverflow           : Integer; asmname '_p_FPE_FLTOVF_TRAP'; external;
  499.   FPERealDivisionByZero     : Integer; asmname '_p_FPE_FLTDIV_TRAP'; external;
  500.   FPERealUnderflow          : Integer; asmname '_p_FPE_FLTUND_TRAP'; external;
  501.   FPEDecimalOverflow        : Integer; asmname '_p_FPE_DECOVF_TRAP'; external;
  502.  
  503. { Returns a description for a signal }
  504. function  StrSignal (Signal : Integer) : TString; asmname '_p_strsignal';
  505.  
  506. { Sends a signal to a process. Returns True if successful. If Signal
  507.   is 0, it doesn't send a signal, but still checks whether it would
  508.   be possible to send a signal to the given process. }
  509. function  Kill (PID, Signal : Integer) : Boolean; asmname '_p_kill';
  510.  
  511. const
  512.   AnyChild = - 1;
  513.  
  514. { Waits for a child process with the given PID (or any child process
  515.   if PID = AnyChild) to terminate or be stopped. Returns the PID of
  516.   the process. WStatus will contain the status and can be evaluated
  517.   with StatusExited etc.. If nothing happened, and Block is False,
  518.   the function will return 0, and WStatus will be 0. If an error
  519.   occurred (especially on single tasking systems where WaitPID is
  520.   not possible), the function will return a negative value, and
  521.   WStatus will be 0. }
  522. function  WaitPID (PID : Integer; var WStatus : Integer; Block : Boolean) : Integer; asmname '_p_waitpid';
  523.  
  524. { Sets the process group of Process (or the current one if Process
  525.   is 0) to ProcessGroup (or its PID if ProcessGroup is 0). Returns
  526.   True if successful. }
  527. function  SetProcessGroup (Process, ProcessGroup : Integer) : Boolean; asmname '_p_setpgid';
  528.  
  529. { Sets the process group of a terminal given by Terminal (as a file
  530.   handle) to ProcessGroup. ProcessGroup must be the ID of a process
  531.   group in the same session. Returns True if successful. }
  532. function  SetTerminalProcessGroup (Terminal, ProcessGroup : Integer) : Boolean; asmname '_p_tcsetpgrp';
  533.  
  534. { Returns the process group of a terminal given by Terminal (as a
  535.   file handle), or -1 on error. }
  536. function  GetTerminalProcessGroup (Terminal : Integer) : Integer; asmname '_p_tcgetpgrp';
  537.  
  538. { Returns the file name of the terminal device that is open on the
  539.   file f. Returns nil if (and only if) f is not open or not
  540.   connected to a terminal. }
  541. function  GetTerminalName (protected var f : AnyFile) : CString; asmname '_p_ttyname';
  542.  
  543. { Set the standard input's signal generation, if it is a terminal. }
  544. procedure SetInputSignals (Signals : Boolean); asmname '_p_set_isig';
  545.  
  546. { Get the standard input's signal generation, if it is a terminal. }
  547. function  GetInputSignals : Boolean;           asmname '_p_get_isig';
  548.  
  549. { Returns the real or effective user ID of the process. }
  550. function  UserID  (Effective : Boolean) : Integer; asmname '_p_uid';
  551.  
  552. { Returns the real or effective group ID of the process. }
  553. function  GroupID (Effective : Boolean) : Integer; asmname '_p_gid';
  554.  
  555. { ================= COMMAND LINE OPTION PARSING ================== }
  556.  
  557. const
  558.   EndOfOptions      = #255;
  559.   NoOption          = #1;
  560.   UnknownOption     = '?';
  561.   LongOption        = #0;
  562.   UnknownLongOption = '?';
  563.  
  564. var
  565.   FirstNonOption         : Integer; asmname '_p_first_non_option';         external;
  566.   HasOptionArgument      : Boolean; asmname '_p_has_option_argument';      external;
  567.   OptionArgument         : TString; asmname '_p_option_argument';          external;
  568.   UnknownOptionCharacter : Char;    asmname '_p_unknown_option_character'; external;
  569.   GetOptErrorFlag        : Boolean; asmname '_p_getopt_error_flag';        external;
  570.  
  571. {
  572.   Parses command line arguments for options and returns the next
  573.   one.
  574.  
  575.   If a command line argument starts with `-', and is not exactly `-'
  576.   or `--', then it is an option element. The characters of this
  577.   element (aside from the initial `-') are option characters. If
  578.   `GetOpt' is called repeatedly, it returns successively each of the
  579.   option characters from each of the option elements.
  580.  
  581.   If `GetOpt' finds another option character, it returns that
  582.   character, updating `FirstNonOption' and internal variables so
  583.   that the next call to `GetOpt' can resume the scan with the
  584.   following option character or command line argument.
  585.  
  586.   If there are no more option characters, `GetOpt' returns
  587.   EndOfOptions. Then `FirstNonOption' is the index of the first
  588.   command line argument that is not an option. (The command line
  589.   arguments have been permuted so that those that are not options
  590.   now come last.)
  591.  
  592.   OptString must be of the form `[+|-]abcd:e:f:g::h::i::'.
  593.  
  594.   a, b, c are options without arguments
  595.   d, e, f are options with required arguments
  596.   g, h, i are options with optional arguments
  597.  
  598.   Arguments are text following the option character in the same
  599.   command line argument, or the text of the following command line
  600.   argument. They are returned in OptionArgument. If an option has no
  601.   argument, OptionArgument is empty. The variable HasOptionArgument
  602.   tells whether an option has an argument. This is mostly useful for
  603.   options with optional arguments, if one wants to distinguish an
  604.   empty argument from no argument.
  605.  
  606.   If the first character of OptString is `+', GetOpt stops at the
  607.   first non-option argument.
  608.  
  609.   If it is `-', GetOpt treats non-option arguments as options and
  610.   return NoOption for them.
  611.  
  612.   Otherwise, GetOpt permutes arguments and handles all options,
  613.   leaving all non-options at the end. However, if the environment
  614.   variable POSIXLY_CORRECT is set, the default behaviour is to stop
  615.   at the first non-option argument, as with `+'.
  616.  
  617.   The special argument `--' forces an end of option-scanning
  618.   regardless of the first character of OptString. In the case of
  619.   `-', only `--' can cause GetOpt to return EndOfOptions with
  620.   FirstNonOption <= ParamCount.
  621.  
  622.   If an option character is seen that is not listed in OptString,
  623.   UnknownOption is returned. The unrecognized option character is
  624.   stored in UnknownOptionCharacter. Unless GetOptErrorFlag is set to
  625.   False, an error message is printed to StdErr automatically.
  626. }
  627. function GetOpt (const OptString : String) : Char; asmname '_p_getopt';
  628.  
  629. type
  630.   OptArgType = (NoArgument, RequiredArgument, OptionalArgument);
  631.  
  632.   OptionType = record
  633.     Name     : CString;
  634.     Argument : OptArgType;
  635.     Flag     : ^Char; { if nil, V is returned. Otherwise, Flag^ is }
  636.     V        : Char   { set to V, and LongOption is returned }
  637.   end;
  638.  
  639. {
  640.   Recognize short options, described by OptString as above, and long
  641.   options, described by LongOptions.
  642.  
  643.   Long-named options begin with `--' instead of `-'. Their names may
  644.   be abbreviated as long as the abbreviation is unique or is an
  645.   exact match for some defined option. If they have an argument, it
  646.   follows the option name in the same argument, separated from the
  647.   option name by a `=', or else the in next argument. When GetOpt
  648.   finds a long-named option, it returns LongOption if that option's
  649.   `Flag' field is non-nil, and the value of the option's `V' field
  650.   if the `Flag' field is nil.
  651.  
  652.   LongIndex, if not null, returns the index in LongOptions of the
  653.   long-named option found. It is only valid when a long-named option
  654.   has been found by the most recent call.
  655.  
  656.   If LongOnly is set, `-' as well as `--' can indicate a long
  657.   option. If an option that starts with `-' (not `--') doesn't match
  658.   a long option, but does match a short option, it is parsed as a
  659.   short option instead. If an argument has the form `-f', where f is
  660.   a valid short option, don't consider it an abbreviated form of a
  661.   long option that starts with `f'. Otherwise there would be no way
  662.   to give the `-f' short option. On the other hand, if there's a
  663.   long option `fubar' and the argument is `-fu', do consider that an
  664.   abbreviation of the long option, just like `--fu', and not `-f'
  665.   with argument `u'. This distinction seems to be the most useful
  666.   approach.
  667.  
  668.   As an additional feature (not present in the C counterpart), if
  669.   the last character of OptString is `-' (after a possible starting
  670.   `+' or `-' character), or OptString is empty, all long options
  671.   with a nil `Flag' field will automatically be recognized as short
  672.   options with the character given by the `V' field. This means, in
  673.   the common (and recommended) case that all short options have long
  674.   equivalents, you can simply pass an empty OptString (or pass `+-'
  675.   or `--' as OptString if you want this behaviour, see the comment
  676.   for GetOpt), and you will only have to maintain the LongOptions
  677.   array when you add or change options.
  678. }
  679. function GetOptLong (const OptString : String; var LongOptions : array [m .. n : Integer] of OptionType { can be null };
  680.                      var LongIndex : Integer { can be null }; LongOnly : Boolean) : Char; asmname '_p_getopt_long';
  681.  
  682. { Reset GetOpt's state and make the next GetOpt or GetOptLong start
  683.   (again) with the StartArgument'th argument (may be 1). This is
  684.   useful for special purposes only. It is *necessary* to do this
  685.   after altering the contents of CParamCount/CParameters (which is
  686.   not usually done, either). }
  687. procedure ResetGetOpt (StartArgument : Integer); asmname '_p_ResetGetOpt';
  688.  
  689. { =========================== PEXECUTE =========================== }
  690.  
  691. const
  692.   PExecute_First   = 1;
  693.   PExecute_Last    = 2;
  694.   PExecute_One     = PExecute_First or PExecute_Last;
  695.   PExecute_Search  = 4;
  696.   PExecute_Verbose = 8;
  697.  
  698. {
  699.   PExecute: execute a program.
  700.  
  701.   Program and Arguments are the arguments to execv/execvp.
  702.  
  703.   Flags and PExecute_Search is non-zero if $PATH should be searched
  704.   (It's not clear that GCC passes this flag correctly). Flags and
  705.   PExecute_First is nonzero for the first process in chain. Flags
  706.   and PExecute_Last is nonzero for the last process in chain.
  707.  
  708.   The result is the pid on systems like Unix where we fork/exec and
  709.   on systems like MS-Windows and OS2 where we use spawn. It is up to
  710.   the caller to wait for the child.
  711.  
  712.   The result is the exit code on systems like MSDOS where we spawn
  713.   and wait for the child here.
  714.  
  715.   Upon failure, ErrMsg is set to the text of the error message,
  716.   and -1 is returned. `errno' is available to the caller to use.
  717.  
  718.   PWait: cover function for wait.
  719.  
  720.   PID is the process id of the task to wait for. Status is the
  721.   `status' argument to wait. Flags is currently unused (allows
  722.   future enhancement without breaking upward compatibility). Pass 0
  723.   for now.
  724.  
  725.   The result is the process ID of the child reaped, or -1 for
  726.   failure.
  727.  
  728.   On systems that don't support waiting for a particular child, PID
  729.   is ignored. On systems like MSDOS that don't really multitask
  730.   PWait is just a mechanism to provide a consistent interface for
  731.   the caller.
  732. }
  733. function PExecute (ProgramName : CString; Arguments : PCStrings; var ErrMsg : String; Flags : Integer) : Integer; asmname '_p_pexecute';
  734. function PWait (PID : Integer; var Status : Integer; Flags : Integer) : Integer; asmname 'pwait';
  735.  
  736. { ==================== TIME HANDLING ROUTINES ==================== }
  737.  
  738. { Time and date routines for Extended Pascal, from time.pas }
  739.  
  740. const
  741.   DateLength = 11; { from types.h }
  742.   TimeLength = 8;  { from types.h }
  743.   InvalidYear = - MaxInt;
  744.  
  745. type
  746.   UnixTimeType = LongInt; { This is hard-coded in the compiler. Do not change here. }
  747.   MicroSecondTimeType = LongInt;
  748.  
  749.   DateString = packed array [1 .. DateLength] of Char;
  750.   TimeString = packed array [1 .. TimeLength] of Char;
  751.  
  752. var
  753.   { DayOfWeekName is a constant and therefore does not respect the
  754.     locale. Therefore, it's recommended to use FormatTime instead. }
  755.   DayOfWeekName : array [0 .. 6] of String [9]; asmname '_p_downame'; external;
  756.  
  757.   { MonthName is a constant and therefore does not respect the
  758.     locale. Therefore, it's recommended to use FormatTime instead. }
  759.   MonthName : array [1 .. 12] of String [9]; asmname '_p_monthname'; external;
  760.  
  761. function  GetDayOfWeek (Day, Month, Year : Integer) : Integer;                                            asmname '_p_dayofweek';
  762. procedure UnixTimeToTimeStamp (UnixTime : UnixTimeType; var aTimeStamp : TimeStamp);                      asmname '_p_unix_time_to_time_stamp';
  763. function  TimeStampToUnixTime (protected var aTimeStamp : TimeStamp) : UnixTimeType;                      asmname '_p_time_stamp_to_unix_time';
  764. function  GetMicroSecondTime : MicroSecondTimeType;                                                       asmname '_p_get_micro_second_time';
  765.  
  766. { Is the year a leap year? }
  767. function  IsLeapYear (Year : Integer) : Boolean;                                                          asmname '_p_is_leap_year';
  768.  
  769. { Returns the length of the month, taking leap years into account. }
  770. function  MonthLength (Month, Year : Integer) : Integer;                                                  asmname '_p_month_length';
  771.  
  772. procedure Sleep (Seconds : Integer);                                                                      asmname '_p_sleep';
  773. procedure SleepMicroSeconds (MicroSeconds : Integer);                                                     asmname '_p_sleep_microseconds';
  774. function  Alarm (Seconds : Integer) : Integer;                                                            asmname '_p_alarm';
  775. procedure UnixTimeToTime (UnixTime : UnixTimeType; var Year, Month, Day, Hour, Minute, Second : Integer); asmname '_p_unix_time_to_time';
  776. function  TimeToUnixTime (Year, Month, Day, Hour, Minute, Second : Integer) : UnixTimeType;               asmname '_p_time_to_unix_time';
  777.  
  778. { Get the real time. MicroSecond can be null and is ignored then. }
  779. function  GetUnixTime (var MicroSecond : Integer) : UnixTimeType;                                         asmname '_p_get_unix_time';
  780.  
  781. { Get the CPU time used. MicroSecond can be null and is ignored then.
  782.   Now, GetCPUTime can measure long CPU times reliably on most systems
  783.   (e.g. Solaris where it didn't work before). }
  784. function  GetCPUTime (var MicroSecond : Integer) : Integer;                                               asmname '_p_get_cpu_time';
  785.  
  786. {
  787.   Formats a TimeStamp value according to a Format string. The format
  788.   string can contain date/time items consisting of `%', followed by
  789.   the specifiers listed below. All characters outside of these items
  790.   are copied to the result unmodified. The specifiers correspond to
  791.   those of the C function strftime(), including POSIX.2 and glibc
  792.   extensions and some more extensions. The extensions are also
  793.   available on systems whose strftime() doesn't support them.
  794.  
  795.   The following modifiers may appear after the `%':
  796.  
  797.   `_'  The item is left padded with spaces to the given or default
  798.        width.
  799.  
  800.   `-'  The item is not padded at all.
  801.  
  802.   `0'  The item is left padded with zeros to the given or default
  803.        width.
  804.  
  805.   `/'  The item is right trimmed if it is longer than the given
  806.        width.
  807.  
  808.   `^'  The item is converted to upper case.
  809.  
  810.   `~'  The item is converted to lower case.
  811.  
  812.   After zero or more of these flags, an optional width may be
  813.   specified for padding and trimming. It must be given as a decimal
  814.   number (not starting with `0' since `0' has a meaning of its own,
  815.   see above).
  816.  
  817.   Afterwards, the following optional modifiers may follow. Their
  818.   meaning is locale-dependent, and many systems and locales just
  819.   ignore them.
  820.  
  821.   `E'  Use the locale's alternate representation for date and time.
  822.        In a Japanese locale, for example, `%Ex' might yield a date
  823.        format based on the Japanese Emperors' reigns.
  824.  
  825.   `O'  Use the locale's alternate numeric symbols for numbers. This
  826.        modifier applies only to numeric format specifiers.
  827.  
  828.   Finally, exactly one of the following specifiers must appear. The
  829.   padding rules listed here are the defaults that can be overriden
  830.   with the modifiers listed above.
  831.  
  832.   `a'  The abbreviated weekday name according to the current locale.
  833.  
  834.   `A'  The full weekday name according to the current locale.
  835.  
  836.   `b'  The abbreviated month name according to the current locale.
  837.  
  838.   `B'  The full month name according to the current locale.
  839.  
  840.   `c'  The preferred date and time representation for the current
  841.        locale.
  842.  
  843.   `C'  The century of the year. This is equivalent to the greatest
  844.        integer not greater than the year divided by 100.
  845.  
  846.   `d'  The day of the month as a decimal number (`01' .. `31').
  847.  
  848.   `D'  The date using the format `%m/%d/%y'. NOTE: Don't use this
  849.        format if it can be avoided. Things like this caused Y2K
  850.        bugs!
  851.  
  852.   `e'  The day of the month like with `%d', but padded with blanks
  853.        (` 1' .. `31').
  854.  
  855.   `F'  The date using the format `%Y-%m-%d'. This is the form
  856.        specified in the ISO 8601 standard and is the preferred form
  857.        for all uses.
  858.  
  859.   `g'  The year corresponding to the ISO week number, but without
  860.        the century (`00' .. `99'). This has the same format and
  861.        value as `y', except that if the ISO week number (see `V')
  862.        belongs to the previous or next year, that year is used
  863.        instead. NOTE: Don't use this format if it can be avoided.
  864.        Things like this caused Y2K bugs!
  865.  
  866.   `G'  The year corresponding to the ISO week number. This has the
  867.        same format and value as `Y', except that if the ISO week
  868.        number (see `V') belongs to the previous or next year, that
  869.        year is used instead.
  870.  
  871.   `h'  The abbreviated month name according to the current locale.
  872.        This is the same as `b'.
  873.  
  874.   `H'  The hour as a decimal number, using a 24-hour clock
  875.        (`00' .. `23').
  876.  
  877.   `I'  The hour as a decimal number, using a 12-hour clock
  878.        (`01' .. `12').
  879.  
  880.   `j'  The day of the year as a decimal number (`001' .. `366').
  881.  
  882.   `k'  The hour as a decimal number, using a 24-hour clock like `H',
  883.        but padded with blanks (` 0' .. `23').
  884.  
  885.   `l'  The hour as a decimal number, using a 12-hour clock like `I',
  886.        but padded with blanks (` 1' .. `12').
  887.  
  888.   `m'  The month as a decimal number (`01' .. `12').
  889.  
  890.   `M'  The minute as a decimal number (`00' .. `59').
  891.  
  892.   `n'  A single newline character.
  893.  
  894.   `p'  Either `AM' or `PM', according to the given time value; or
  895.        the corresponding strings for the current locale. Noon is
  896.        treated as `PM' and midnight as `AM'.
  897.  
  898.   `P'  Either `am' or `pm', according to the given time value; or
  899.        the corresponding strings for the current locale, printed in
  900.        lowercase characters. Noon is treated as `pm' and midnight as
  901.        `am'.
  902.  
  903.   `Q'  The fractional part of the second. This format has special
  904.        effects on the modifiers. The width, if given, determines the
  905.        number of digits to output. Therefore, no actual clipping or
  906.        trimming is done. However, if padding with spaces is
  907.        specified, any trailing (i.e., left!) zeros are converted to
  908.        spaces, and if "no padding" is specified, they are removed.
  909.        The default is "padding with zeros", i.e. trailing zeros are
  910.        left unchanged. The digits are cut when necessary without
  911.        rounding (otherwise, the value would not be consistent with
  912.        the seconds given by `S' and `s'). Note that GPC's TimeStamp
  913.        currently provides for microsecond resolution, so there are
  914.        at most 6 valid digits (which is also the default width), any
  915.        further digits will be 0 (but if TimeStamp will ever change,
  916.        this format will be adjusted). However, the actual resolution
  917.        provided by the operating system via GetTimeStamp etc. may be
  918.        far lower (e.g., ~1/18s under Dos).
  919.  
  920.   `r'  The complete time using the AM/PM format of the current
  921.        locale.
  922.  
  923.   `R'  The hour and minute in decimal numbers using the format
  924.        `%H:%M'.
  925.  
  926.   `s'  Unix time, i.e. the number of seconds since the epoch, i.e.,
  927.        since 1970-01-01 00:00:00 UTC. Leap seconds are not counted
  928.        unless leap second support is available.
  929.  
  930.   `S'  The seconds as a decimal number (`00' .. `60').
  931.  
  932.   `t'  A single tab character.
  933.  
  934.   `T'  The time using decimal numbers using the format `%H:%M:%S'.
  935.  
  936.   `u'  The day of the week as a decimal number (`1' .. `7'), Monday
  937.        being `1'.
  938.  
  939.   `U'  The week number of the current year as a decimal number
  940.        (`00' .. `53'), starting with the first Sunday as the first
  941.        day of the first week. Days preceding the first Sunday in the
  942.        year are considered to be in week `00'.
  943.  
  944.   `V'  The ISO 8601:1988 week number as a decimal number
  945.        (`01' .. `53'). ISO weeks start with Monday and end with
  946.        Sunday. Week `01' of a year is the first week which has the
  947.        majority of its days in that year; this is equivalent to the
  948.        week containing the year's first Thursday, and it is also
  949.        equivalent to the week containing January 4. Week `01' of a
  950.        year can contain days from the previous year. The week before
  951.        week `01' of a year is the last week (`52' or `53') of the
  952.        previous year even if it contains days from the new year.
  953.  
  954.   `w'  The day of the week as a decimal number (`0' .. `6'), Sunday
  955.        being `0'.
  956.  
  957.   `W'  The week number of the current year as a decimal number
  958.        (`00' .. `53'), starting with the first Monday as the first
  959.        day of the first week. All days preceding the first Monday in
  960.        the year are considered to be in week `00'.
  961.  
  962.   `x'  The preferred date representation for the current locale, but
  963.        without the time.
  964.  
  965.   `X'  The preferred time representation for the current locale, but
  966.        with no date.
  967.  
  968.   `y'  The year without a century as a decimal number
  969.        (`00' .. `99'). This is equivalent to the year modulo 100.
  970.        NOTE: Don't use this format if it can be avoided. Things like
  971.        this caused Y2K bugs!
  972.  
  973.   `Y'  The year as a decimal number, using the Gregorian calendar.
  974.        Years before the year `1' are numbered `0', `-1', and so on.
  975.  
  976.   `z'  RFC 822/ISO 8601:1988 style numeric time zone (e.g., `-0600'
  977.        or `+0100'), or nothing if no time zone is determinable.
  978.  
  979.   `Z'  The time zone abbreviation (empty if the time zone can't be
  980.        determined).
  981.  
  982.   `%'  (i.e., an item `%%') A literal `%' character.
  983. }
  984. function  FormatTime (const Time : TimeStamp; const Format : String) : TString;                           asmname '_p_format_time';
  985.  
  986. { ==================== FILE HANDLING ROUTINES ==================== }
  987.  
  988. { File handling routines and their support, mostly from files.pas and file.c }
  989.  
  990. type
  991.   FileSizeType = LongInt;
  992.  
  993. procedure GetBinding   (protected var aFile : AnyFile; var aBinding : BindingType); asmname '_p_binding';
  994. procedure ClearBinding (var aBinding : BindingType);                                asmname '_p_clearbinding';
  995.  
  996. { TFDD interface @@ Subject to change! Use with caution! }
  997.  
  998. type
  999.   TOpenMode   = (foNone, foReset, foRewrite, foAppend, foSeekRead, foSeekWrite, foSeekUpdate);
  1000.   TOpenProc   = procedure (var PrivateData; Mode : TOpenMode);
  1001.   TSelectFunc = function  (var PrivateData; Writing : Boolean) : Integer; { called before select(), must return a handle }
  1002.   TSelectProc = procedure (var PrivateData; var ReadSelect, WriteSelect, ExceptSelect : Boolean); { called before and after select() }
  1003.   TReadFunc   = function  (var PrivateData; var   Buffer; Size : SizeType) : SizeType;
  1004.   TWriteFunc  = function  (var PrivateData; const Buffer; Size : SizeType) : SizeType;
  1005.   TFileProc   = procedure (var PrivateData);
  1006.   TFlushProc  = TFileProc;
  1007.   TCloseProc  = TFileProc;
  1008.   TDoneProc   = TFileProc;
  1009.  
  1010. procedure AssignTFDD (var f : AnyFile;
  1011.                       OpenProc    : TOpenProc;
  1012.                       SelectFunc  : TSelectFunc;
  1013.                       SelectProc  : TSelectProc;
  1014.                       ReadFunc    : TReadFunc;
  1015.                       WriteFunc   : TWriteFunc;
  1016.                       FlushProc   : TFlushProc;
  1017.                       CloseProc   : TCloseProc;
  1018.                       DoneProc    : TDoneProc;
  1019.                       PrivateData : Pointer);       asmname '_p_assign_tfdd';
  1020.  
  1021. procedure SetTFDD    (var f : AnyFile;
  1022.                       OpenProc    : TOpenProc;
  1023.                       SelectFunc  : TSelectFunc;
  1024.                       SelectProc  : TSelectProc;
  1025.                       ReadFunc    : TReadFunc;
  1026.                       WriteFunc   : TWriteFunc;
  1027.                       FlushProc   : TFlushProc;
  1028.                       CloseProc   : TCloseProc;
  1029.                       DoneProc    : TDoneProc;
  1030.                       PrivateData : Pointer);       asmname '_p_set_tfdd';
  1031.  
  1032. { Any parameter except f may be null }
  1033. procedure GetTFDD    (var f : AnyFile;
  1034.                       var OpenProc    : TOpenProc;
  1035.                       var SelectFunc  : TSelectFunc;
  1036.                       var SelectProc  : TSelectProc;
  1037.                       var ReadFunc    : TReadFunc;
  1038.                       var WriteFunc   : TWriteFunc;
  1039.                       var FlushProc   : TFlushProc;
  1040.                       var CloseProc   : TCloseProc;
  1041.                       var DoneProc    : TDoneProc;
  1042.                       var PrivateData : Pointer);   asmname '_p_get_tfdd';
  1043.  
  1044. type
  1045.   Natural = 1 .. MaxInt;
  1046.   IOSelectEvents = (SelectReadOrEOF, SelectRead, SelectEOF, SelectWrite, SelectException, SelectAlways);
  1047.  
  1048. const
  1049.   IOSelectEventMin = (*Low (IOSelectEvents);*)SelectReadOrEOF;
  1050.   IOSelectEventMax = Pred (SelectAlways);
  1051.  
  1052. type
  1053.   IOSelectType = record
  1054.     f : PAnyFile;
  1055.     Wanted : set of IOSelectEvents;
  1056.     Occurred : set of IOSelectEventMin .. IOSelectEventMax
  1057.   end;
  1058.  
  1059. { Waits for one of several events to happen. Returns when one or
  1060.   more of the wanted events for one of the files occur. If they have
  1061.   already occurred before calling the function, it returns
  1062.   immediately. MicroSeconds can specify a timeout. If it is 0, the
  1063.   function will return immediately, whether or not an event has
  1064.   occurred. If it is negative, the function will wait forever until
  1065.   an event occurs. The Events parameter can be null, in which case
  1066.   the function only waits for the timeout. If any of the file
  1067.   pointers (f) in Events are nil or the files pointed to are closed,
  1068.   they are simply ignored for convenience.
  1069.  
  1070.   It returns the index of one of the files for which any event has
  1071.   occurred. If events have occurred for several files, is it
  1072.   undefined which of these file's index is returned. If no event
  1073.   occurs until the timeout, 0 is returned. If an error occurs or the
  1074.   target system does not have a select() system call and Events is
  1075.   not null, a negative value is returned. In the Occurred field of
  1076.   the elements of Events, events that have occurred are set. The
  1077.   state of events not wanted is undefined.
  1078.  
  1079.   The possible events are:
  1080.   SelectReadOrEOF: the file is at EOF or data can be read now.
  1081.   SelectRead:      data can be read now.
  1082.   SelectEOF:       the file is at EOF.
  1083.   SelectWrite:     data can be written now.
  1084.   SelectException: an exception occurred on the file.
  1085.   SelectAlways:    if this is set, *all* requested events will be
  1086.                    checked for this file in any case. Otherwise,
  1087.                    checks may be skipped if already another event
  1088.                    for this or another file was found.
  1089.  
  1090.   Notes:
  1091.   Checking for EOF requires some reading ahead internally (just like
  1092.   the EOF function) which can be avoided by setting SelectReadOrEOF
  1093.   instead of SelectRead and SelectEOF. If this is followed by, e.g.,
  1094.   a BlockRead with 4 parameters, the last parameter will be 0 if and
  1095.   only the file is at EOF, and otherwise, data will be read directly
  1096.   from the file without reading ahead and buffering.
  1097.  
  1098.   SelectAlways should be set for files for which events are
  1099.   considered to be of higher priority than others. Otherwise, if one
  1100.   is interested in just any event, not setting SelectAlways may be a
  1101.   little faster. }
  1102. function IOSelect (var Events : array [m .. n : Natural] of IOSelectType; MicroSeconds : MicroSecondTimeType) : Integer; asmname '_p_ioselect';
  1103.  
  1104. { A simpler interface to SelectIO for the most common use. Waits for
  1105.   SelectReadOrEOF on all files and returns an index. }
  1106. function IOSelectRead (const Files : array [m .. n : Natural] of PAnyFile; MicroSeconds : MicroSecondTimeType) : Integer; asmname '_p_ioselectread';
  1107.  
  1108. procedure AssignFile   (var T : AnyFile; const Name : String);                     asmname '_p_assign';
  1109. procedure AssignBinary (var T : Text; const Name : String);                        asmname '_p_assign_binary';
  1110. procedure AssignHandle (var T : AnyFile; Handle : Integer);                        asmname '_p_assign_handle';
  1111.  
  1112. { BP compatible seeking routines }
  1113. function  SeekEOF  (var f : Text) : Boolean; asmname '_p_seekeof';
  1114. function  SeekEOLn (var f : Text) : Boolean; asmname '_p_seekeoln';
  1115.  
  1116. { Under development }
  1117. procedure AnyStringTFDD_Reset (var f : AnyFile; var Buf : ConstAnyString); asmname '_p_anystring_tfdd_reset';
  1118. (*procedure AnyStringTFDD_Rewrite (var f : AnyFile; var Buf : VarAnyString); asmname '_p_anystring_tfdd_rewrite';*)
  1119. procedure StringTFDD_Reset (var f : AnyFile; var Buf : ConstAnyString; const s : String); asmname '_p_string_tfdd_reset';
  1120. (*procedure StringTFDD_Rewrite (var f : AnyFile; var Buf : VarAnyString; var s : String); asmname '_p_string_tfdd_rewrite';*)
  1121.  
  1122. (*@@iocritical*)procedure FileMove (var f : AnyFile; NewName : CString; Overwrite : Boolean); asmname '_p_mv';
  1123.  
  1124. { Flags that can be ORed into FileMode. The default value of
  1125.   FileMode is FileMode_Reset_ReadWrite. The somewhat confusing
  1126.   values are meant to be compatible to BP (as far as BP supports
  1127.   them). }
  1128. const
  1129.   { Allow writing to binary files opened with Reset }
  1130.   FileMode_Reset_ReadWrite      = 2;
  1131.  
  1132.   { Do not allow reading from files opened with Rewrite }
  1133.   FileMode_Rewrite_WriteOnly    = 4;
  1134.  
  1135.   { Do not allow reading from files opened with Extend }
  1136.   FileMode_Extend_WriteOnly     = 8;
  1137.  
  1138.   { Allow writing to text files opened with Reset }
  1139.   FileMode_Text_Reset_ReadWrite = $100;
  1140.  
  1141. { File mode constants that are ORed for BindingType.Mode and ChMod.
  1142.   The values below are valid for all OSs (as far as supported). If
  1143.   the OS uses different values, they're converted internally. }
  1144. const
  1145.   fm_SetUID           = 8#4000;
  1146.   fm_SetGID           = 8#2000;
  1147.   fm_Sticky           = 8#1000;
  1148.   fm_UserReadable     = 8#400;
  1149.   fm_UserWritable     = 8#200;
  1150.   fm_UserExecutable   = 8#100;
  1151.   fm_GroupReadable    = 8#40;
  1152.   fm_GroupWritable    = 8#20;
  1153.   fm_GroupExecutable  = 8#10;
  1154.   fm_OthersReadable   = 8#4;
  1155.   fm_OthersWritable   = 8#2;
  1156.   fm_OthersExecutable = 8#1;
  1157.  
  1158. type
  1159.   TextFile = Text;
  1160.  
  1161.   StatFSBuffer = record
  1162.     BlockSize, BlocksTotal, BlocksFree : LongestInt;
  1163.     FilesTotal, FilesFree : Integer
  1164.   end;
  1165.  
  1166. procedure CloseFile    (          var aFile : (*@@Any*)File);                                        asmname '_p_close';
  1167. (*@@IO critical*) procedure ChMod        (          var aFile : AnyFile; Mode : Integer);                        asmname '_p_chmod';
  1168. (*@@IO critical*) procedure StatFS       (Path : CString; var Buf : StatFSBuffer);                               asmname '_p_statfs';
  1169.  
  1170. { Checks if data are available to be read from aFile. This is similar to
  1171.   `not EOF (aFile)', but does not block on "files" that can grow, like TTYs
  1172.   or pipes. }
  1173. function  CanRead      (var aFile : AnyFile) : Boolean;                                        asmname '_p_canread';
  1174.  
  1175. { Get the file handle. }
  1176. function  FileHandle   (protected var aFile : AnyFile) : Integer;                                        asmname '_p_filehandle';
  1177.  
  1178. { Lock files }
  1179. function  FileLock   (var aFile : AnyFile; WriteLock, Block : Boolean) : Boolean; asmname '_p_filelock';
  1180. function  FileUnlock (var aFile : AnyFile) : Boolean; asmname '_p_fileunlock';
  1181.  
  1182. const
  1183.   mm_Readable   = 1;
  1184.   mm_Writable   = 2;
  1185.   mm_Executable = 4;
  1186.  
  1187. function MemoryMap (Start : Pointer; Length : SizeType; Access : Integer; Shared : Boolean;
  1188.                     var aFile : AnyFile; Offset : FileSizeType) : Pointer; asmname '_p_mmap';
  1189. procedure MemoryUnMap (Start : Pointer; Length : SizeType); asmname '_p_munmap';
  1190.  
  1191. { File name routines, from filename.pas }
  1192.  
  1193. {
  1194.   Define constants for different systems:
  1195.  
  1196.   OSDosFlag:         flag to indicate whether the target system is
  1197.                      Dos
  1198.  
  1199.   QuotingCharacter:  the character used to quote wild cards and
  1200.                      other special characters (#0 if not available)
  1201.  
  1202.   PathSeparator:     the separator of multiple paths, e.g. in the
  1203.                      PATH environment variable
  1204.  
  1205.   DirSeparator:      the separator of the directories within a full
  1206.                      file name
  1207.  
  1208.   DirSeparators:     a set of all possible directory and drive name
  1209.                      separators
  1210.  
  1211.   ExtSeparator:      the separator of a file name extension
  1212.  
  1213.   DirRoot:           the name of the root directory
  1214.  
  1215.   DirSelf:           the name of a directory in itself
  1216.  
  1217.   DirParent:         the name of the parent directory
  1218.  
  1219.   MaskNoStdDir:      a file name mask that matches all names except
  1220.                      the standard directories DirSelf and DirParent
  1221.  
  1222.   NullDeviceName:    the full file name of the null device
  1223.  
  1224.   TTYDeviceName:     the full file name of the current TTY
  1225.  
  1226.   ConsoleDeviceName: the full file name of the system console. On
  1227.                      Dos systems, this is the same as the TTY, but
  1228.                      on systems that allow remote login, this is a
  1229.                      different thing and may reach a completely
  1230.                      different user than the one running the
  1231.                      program, so use with care.
  1232.  
  1233.   EnvVarCharsFirst:  the characters accepted at the beginning of the
  1234.                      name of an environment variable without quoting
  1235.  
  1236.   EnvVarChars:       the characters accepted in the name of an
  1237.                      environment variable without quoting
  1238.  
  1239.   PathEnvVar:        the name of the environment variable which
  1240.                      (usually) contains the executable search path
  1241.  
  1242.   ShellEnvVar:       the name of the environment variable which
  1243.                      (usually) contains the path of the shell
  1244.                      executable (see GetShellPath)
  1245.  
  1246.   ShellExecCommand:  the option to the (default) shell to execute
  1247.                      the command specified in the following argument
  1248.                      (see GetShellPath)
  1249.  
  1250.   ConfigFileMask:    a mask for the option file name as returned by
  1251.                      ConfigFileName
  1252.  
  1253.   FileNamesCaseSensitive:
  1254.                      flag to indicate whether file names are case
  1255.                      sensitive
  1256. }
  1257.  
  1258. const
  1259.   UnixShellEnvVar        = 'SHELL';
  1260.   UnixShellExecCommand   = '-c';
  1261.  
  1262. {$ifdef __OS_DOS__}
  1263.  
  1264. const
  1265.   OSDosFlag              = True;
  1266.   QuotingCharacter       = #0;
  1267.   PathSeparator          = {$ifdef __CYGWIN32__} ':' {$else} ';' {$endif};
  1268.   DirSeparator           = '\';
  1269.   DirSeparators          = [':', '\', '/'];
  1270.   ExtSeparator           = '.';
  1271.   DirRoot                = '\';
  1272.   DirSelf                = '.';
  1273.   DirParent              = '..';
  1274.   MaskNoStdDir           = '{*,.[^.],..?*}';
  1275.   NullDeviceName         = 'nul';
  1276.   TTYDeviceName          = 'con';
  1277.   ConsoleDeviceName      = 'con';
  1278.   EnvVarCharsFirst       = ['A' .. 'Z', 'a' .. 'z', '_'];
  1279.   EnvVarChars            = EnvVarCharsFirst + ['0' .. '9'];
  1280.   PathEnvVar             = 'PATH';
  1281.   ShellEnvVar            = 'COMSPEC';
  1282.   ShellExecCommand       = '/c';
  1283.   ConfigFileMask         = '*.cfg';
  1284.   FileNamesCaseSensitive = False;
  1285.  
  1286. {$else}
  1287.  
  1288. const
  1289.   OSDosFlag              = False;
  1290.   QuotingCharacter       = '\';
  1291.   PathSeparator          = ':';
  1292.   DirSeparator           = '/';
  1293.   DirSeparators          = ['/'];
  1294.   ExtSeparator           = '.';
  1295.   DirRoot                = '/';
  1296.   DirSelf                = '.';
  1297.   DirParent              = '..';
  1298.   MaskNoStdDir           = '{*,.[^.],..?*}';
  1299.   NullDeviceName         = '/dev/null';
  1300.   TTYDeviceName          = '/dev/tty';
  1301.   ConsoleDeviceName      = '/dev/console';
  1302.   EnvVarCharsFirst       = ['A' .. 'Z', 'a' .. 'z', '_'];
  1303.   EnvVarChars            = EnvVarCharsFirst + ['0' .. '9'];
  1304.   PathEnvVar             = 'PATH';
  1305.   ShellEnvVar            = UnixShellEnvVar;
  1306.   ShellExecCommand       = UnixShellExecCommand;
  1307.   ConfigFileMask         = '.*';
  1308.   FileNamesCaseSensitive = True;
  1309.  
  1310. {$endif}
  1311.  
  1312. const
  1313.   WildCardChars = ['*', '?', '[', ']'];
  1314.   FileNameSpecialChars = (WildCardChars + SpaceCharacters + ['{', '}', '$', QuotingCharacter]) - DirSeparators;
  1315.  
  1316. type
  1317.   DirPtr = Pointer;
  1318.  
  1319.   { `+ 1' is a waste, but it is so the size of the array is not
  1320.     zero for Count = 0 }
  1321.   PPStrings = ^TPStrings;
  1322.   TPStrings (Count : Cardinal) = array [1 .. Count + 1] of ^String;
  1323.  
  1324.   GlobBuffer = record
  1325.     Result    : PPStrings;
  1326.     Internal1 : Pointer;
  1327.     Internal2 : PCStrings;
  1328.     Internal3 : Integer
  1329.   end;
  1330.  
  1331. { Convert ch to lower case if FileNamesCaseSensitive is False, leave
  1332.   it unchanged otherwise. }
  1333. function  FileNameLoCase (ch : Char) : Char;                               asmname '_p_filenamelocase';
  1334.  
  1335. { Change a file name to use the OS dependent directory separator }
  1336. function  Slash2OSDirSeparator (const s : String) : TString;               asmname '_p_slash2osdirseparator';
  1337.  
  1338. { Change a file name to use '/' as directory separator }
  1339. function  OSDirSeparator2Slash (const s : String) : TString;               asmname '_p_osdirseparator2slash';
  1340.  
  1341. { Like Slash2OSDirSeparator for CStrings -- NOTE: overwrites the
  1342.   CString }
  1343. function  Slash2OSDirSeparator_CString (s : CString) : CString;            asmname '_p_slash2osdirseparator_cstring';
  1344.  
  1345. { Like OSDirSeparator2Slash for CStrings -- NOTE: overwrites the
  1346.   CString }
  1347. function  OSDirSeparator2Slash_CString (s : CString) : CString;            asmname '_p_osdirseparator2slash_cstring';
  1348.  
  1349. { Add a DirSeparator to the end of s, if there is not already one
  1350.   and s denotes an existing directory }
  1351. function  AddDirSeparator (const s : String) : TString;                    asmname '_p_adddirseparator';
  1352.  
  1353. { Like AddDirSeparator, but also if the directory does not exist }
  1354. function  ForceAddDirSeparator (const s : String) : TString;               asmname '_p_forceadddirseparator';
  1355.  
  1356. { Remove all trailing DirSeparators from s, if there are any, as
  1357.   long as removing them doesn't change the meaning (i.e., they don't
  1358.   denote the root directory. }
  1359. function  RemoveDirSeparator (const s : String) : TString;                 asmname '_p_removedirseparator';
  1360.  
  1361. { Returns the current directory using OS dependent directory
  1362.   separators }
  1363. function  GetCurrentDirectory     : TString;                               asmname '_p_get_current_directory';
  1364.  
  1365. { Returns a directory suitable for storing temporary files using OS
  1366.   dependent directory separators. If found, the result always ends
  1367.   in DirSeparator. If no suitable directory is found, an empty
  1368.   string is returned. }
  1369. function  GetTempDirectory        : TString;                               asmname '_p_get_temp_directory';
  1370.  
  1371. { Returns a non-existing file name in the directory given. If the
  1372.   directory doesn't exist or the Directory name is empty, a runtime
  1373.   error is raised, and GetTempFileNameInDirectory returns the empty
  1374.   string. }
  1375. (*@@iocritical*)function  GetTempFileNameInDirectory (const Directory : String) : TString; asmname '_p_get_temp_file_name_in_directory';
  1376.  
  1377. { Returns a non-existing file name in GetTempDirectory. If no temp
  1378.   directory is found, i.e. GetTempDirectory returns the empty
  1379.   string, a runtime error is raised, and GetTempFileName returns the
  1380.   empty string as well. }
  1381. (*@@iocritical*)function  GetTempFileName         : TString;                               asmname '_p_get_temp_file_name';
  1382.  
  1383. { The same as GetTempFileName, but returns a CString allocated from
  1384.   the heap. }
  1385. (*@@iocritical*)function  GetTempFileName_CString : CString;                               asmname '_p_get_temp_file_name_cstring';
  1386.  
  1387. { Get the external name of a file }
  1388. function  FileName (protected var f : AnyFile) : TString;                  asmname '_p_file_name';
  1389.  
  1390. { Returns true if the given file name is an existing plain file }
  1391. function  FileExists      (const aFileName : String) : Boolean;            asmname '_p_file_exists';
  1392.  
  1393. { Returns True if the given file name is an existing directory }
  1394. function  DirectoryExists (const aFileName : String) : Boolean;            asmname '_p_directory_exists';
  1395.  
  1396. { Returns True if the given file name is an existing file, directory
  1397.   or special file (device, pipe, socket, etc.) }
  1398. function  PathExists      (const aFileName : String) : Boolean;            asmname '_p_path_exists';
  1399.  
  1400. { If a file of the given name exists in one of the directories given
  1401.   in DirList (separated by PathSeparator), returns the full path,
  1402.   otherwise returns an empty string. If aFileName already contains
  1403.   an element of DirSeparators, returns Slash2OSDirSeparator
  1404.   (aFileName) if it exists. }
  1405. function  FSearch (const aFileName, DirList : String) : TString;           asmname '_p_fsearch';
  1406.  
  1407. { Like FSearch, but only find executable files. Under Dos, if not
  1408.   found, the function tries appending '.com', '.exe', '.bat' and
  1409.   `.cmd' (the last one only if $COMSPEC points to a `cmd.exe'), so
  1410.   you don't have to specify these extensions in aFileName (and with
  1411.   respect to portability, it might be preferable not to do so). }
  1412. function  FSearchExecutable (const aFileName, DirList : String) : TString; asmname '_p_fsearch_executable';
  1413.  
  1414. { Replaces all occurrences of `$FOO' and `~' in s by the value of
  1415.   the environment variables FOO or HOME, respectively. If a variable
  1416.   is not defined, the function returns False, and s contains the
  1417.   name of the undefined variable (or the empty string if the
  1418.   variable name is invalid, i.e., doesn't start with a character
  1419.   from EnvVarCharsFirst). Otherwise, if all variables are found, s
  1420.   contains the replaced string, and True is returned. }
  1421. function  ExpandEnvironment (var s : String) : Boolean;                    asmname '_p_expand_environment';
  1422.  
  1423. { Expands the given path name to a full path name. Relative paths
  1424.   are expanded using the current directory, and occurrences of
  1425.   DirSelf and DirParent are resolved. Under Dos, the result is
  1426.   converted to lower case and a trailing ExtSeparator (except in a
  1427.   trailing DirSelf or DirParent) is removed, like Dos does. If the
  1428.   directory, i.e. the path without the file name, is invalid, the
  1429.   empty string is returned. }
  1430. function  FExpand       (const Path : String) : TString;                   asmname '_p_fexpand';
  1431.  
  1432. { Like FExpand, but unquotes the directory before expanding it, and
  1433.   quotes WildCardChars again afterwards. Does not check if the
  1434.   directory is valid (because it may contain wild card characters).
  1435.   Symlinks are expanded only in the directory part, not the file
  1436.   name. }
  1437. function  FExpandQuoted (const Path : String) : TString;                   asmname '_p_fexpandquoted';
  1438.  
  1439. { FExpands Path, and then removes the current directory from it, if
  1440.   it is a prefix of it. If OnlyCurDir is set, the current directory
  1441.   will be removed only if Path denotes a file in, not below, it. }
  1442. function  RelativePath (const Path : String; OnlyCurDir, Quoted : Boolean) : TString; asmname '_p_relative_path';
  1443.  
  1444. { Is aFileName a UNC filename? (Always returns False on non-Dos
  1445.   systems.) }
  1446. function  IsUNC (const aFileName : String) : Boolean;                      asmname '_p_IsUNC';
  1447.  
  1448. { Splits a file name into directory, name and extension. Each of
  1449.   Dir, Name and Ext may be null. }
  1450. procedure FSplit (const Path : String; var Dir, Name, Ext : String);       asmname '_p_fsplit';
  1451.  
  1452. { Functions that extract one or two of the parts from FSplit.
  1453.   DirFromPath returns DirSelf + DirSeparator if the path contains no
  1454.   directory. }
  1455. function  DirFromPath     (const Path : String) : TString;                 asmname '_p_dir_from_path';
  1456. function  NameFromPath    (const Path : String) : TString;                 asmname '_p_name_from_path';
  1457. function  ExtFromPath     (const Path : String) : TString;                 asmname '_p_ext_from_path';
  1458. function  NameExtFromPath (const Path : String) : TString;                 asmname '_p_name_ext_from_path';
  1459.  
  1460. { Start reading a directory. If successful, a pointer is returned
  1461.   that can be used for subsequent calls to ReadDir and finally
  1462.   CloseDir. On failure, an I/O error is raised and (in case it is
  1463.   ignored) nil is returned. }
  1464. (*@@iocritical*)function  OpenDir  (const Name : String) : DirPtr;                         asmname '_p_opendir';
  1465.  
  1466. { Reads one entry from the directory Dir, and returns the file name.
  1467.   On errors or end of directory, the empty string is returned. }
  1468. function  ReadDir  (Dir : DirPtr) : TString;                               asmname '_p_readdir';
  1469.  
  1470. { Closes a directory opened with OpenDir. }
  1471. (*@@iocritical*)procedure CloseDir (Dir : DirPtr);                                         asmname '_p_closedir';
  1472.  
  1473. { Returns the first position of a non-quoted character of CharSet in
  1474.   s, or 0 if no such character exists. }
  1475. function  FindNonQuotedChar (Chars : CharSet; const s : String; From : Integer) : Integer; asmname '_p_findnonquotedchar';
  1476.  
  1477. { Returns the first occurence of SubString in s that is not quoted
  1478.   at the beginning, or 0 if no such occurence exists. }
  1479. function  FindNonQuotedStr (const SubString, s : String; From : Integer) : Integer; asmname '_p_findnonquotedstr';
  1480.  
  1481. { Does a string contain non-quoted wildcard characters? }
  1482. function  HasWildCards (const s : String) : Boolean;                       asmname '_p_haswildcards';
  1483.  
  1484. { Does a string contain non-quoted wildcard characters, braces or
  1485.   spaces? }
  1486. function  HasWildCardsOrBraces (const s : String) : Boolean;               asmname '_p_haswildcardsorbraces';
  1487.  
  1488. { Insert QuotingCharacter into s before any special characters }
  1489. function  QuoteFileName (const s : String; const SpecialCharacters : CharSet) : TString; asmname '_p_quote_filename';
  1490.  
  1491. { Remove QuotingCharacter from s }
  1492. function  UnQuoteFileName (const s : String) : TString;                    asmname '_p_unquote_filename';
  1493.  
  1494. { Splits s at non-quoted spaces and expands non-quoted braces like
  1495.   bash does. The result and its entries should be disposed after
  1496.   usage, e.g. with DisposePPStrings. }
  1497. function  BraceExpand (const s : String) : PPStrings;                      asmname '_p_braceexpand';
  1498.  
  1499. { Dispose of a PPStrings array as well as the strings it contains.
  1500.   If you want to keep the strings (by assigning them to other string
  1501.   pointers), you should instead free the PPStrings array with
  1502.   `Dispose'. }
  1503. procedure DisposePPStrings (Strings : PPStrings);                          asmname '_p_DisposePPStrings';
  1504.  
  1505. { Tests if a file name matches a shell wildcard pattern (?, *, []) }
  1506. function  FileNameMatch (const Pattern, Name : String) : Boolean;          asmname '_p_filenamematch';
  1507.  
  1508. { FileNameMatch with BraceExpand }
  1509. function  MultiFileNameMatch (const Pattern, Name : String) : Boolean;     asmname '_p_multifilenamematch';
  1510.  
  1511. { File name globbing }
  1512. { GlobInit is implied by Glob and MultiGlob, not by GlobOn and
  1513.   MultiGlobOn. GlobOn and MultiGlobOn must be called after GlobInit,
  1514.   Glob or MultiGlob. MultiGlob and MultiGlobOn do brace expansion,
  1515.   Glob and GlobOn do not. GlobFree frees the memory allocated by the
  1516.   globbing functions and invalidates the results in Buf. It should
  1517.   be called after globbing. }
  1518. procedure GlobInit    (var Buf : GlobBuffer);                              asmname '_p_globinit';
  1519. procedure Glob        (var Buf : GlobBuffer; const Pattern : String);      asmname '_p_glob';
  1520. procedure GlobOn      (var Buf : GlobBuffer; const Pattern : String);      asmname '_p_globon';
  1521. procedure MultiGlob   (var Buf : GlobBuffer; const Pattern : String);      asmname '_p_multiglob';
  1522. procedure MultiGlobOn (var Buf : GlobBuffer; const Pattern : String);      asmname '_p_multiglobon';
  1523. procedure GlobFree    (var Buf : GlobBuffer);                              asmname '_p_globfree';
  1524.  
  1525. type
  1526.   TPasswordEntry = record
  1527.     UserName, RealName, Password, HomeDirectory, Shell : TString;
  1528.     UID, GID : Integer
  1529.   end;
  1530.  
  1531.   PPasswordEntries = ^TPasswordEntries;
  1532.   TPasswordEntries (Count : Integer) = array [1 .. Count] of TPasswordEntry;
  1533.  
  1534. { Finds a password entry by user name. Returns True if found, False
  1535.   otherwise. }
  1536. function  GetPasswordEntryByName (const UserName : String; var Entry : TPasswordEntry) : Boolean; asmname '_p_getpasswordentrybyname';
  1537.  
  1538. { Finds a password entry by UID. Returns True if found, False
  1539.   otherwise. }
  1540. function  GetPasswordEntryByUID  (UID : Integer; var Entry : TPasswordEntry) : Boolean; asmname '_p_getpasswordentrybyuid';
  1541.  
  1542. { Returns all password entries, or nil if none found. }
  1543. function  GetPasswordEntries : PPasswordEntries; asmname '_p_getpasswordentries';
  1544.  
  1545. { Returns the mount point (Unix) or drive (Dos) which is part of the
  1546.   given path. If the path does not contain any (i.e., is a relative
  1547.   path), an empty string is returned. Therefore, if you want to get
  1548.   the mount point or drive in any case, apply `FExpand' or
  1549.   `RealPath' to the argument. }
  1550. function  GetMountPoint (const Path : String) = Result : TString; asmname '_p_GetMountPoint';
  1551.  
  1552. type
  1553.   TSystemInfo = record
  1554.     OSName,
  1555.     OSRelease,
  1556.     OSVersion,
  1557.     MachineType,
  1558.     HostName,
  1559.     DomainName : TString
  1560.   end;
  1561.  
  1562. { Returns system information if available. Fields not available will
  1563.   be empty. }
  1564. function  SystemInfo : TSystemInfo; asmname '_p_SystemInfo';
  1565.  
  1566. { Returns the path to the shell (as the return value) and the option
  1567.   that makes it execute the command specified in the following
  1568.   argument (in `Option'). Usually these are the environment value of
  1569.   ShellEnvVar, and ShellExecCommand, but on Dos systems, the
  1570.   function will first try UnixShellEnvVar, and UnixShellExecCommand
  1571.   because ShellEnvVar will usually point to command.com, but
  1572.   UnixShellEnvVar can point to bash which is usually a better choice
  1573.   when present. If UnixShellEnvVar is not set, or the shell given
  1574.   does not exist, it will use ShellEnvVar, and ShellExecCommand.
  1575.   Option may be null (in case you want to invoke the shell
  1576.   interactively). }
  1577. function  GetShellPath (var Option : String) : TString; asmname '_p_GetShellPath';
  1578.  
  1579. { Returns the path of the running executable. NOTE: On most systems,
  1580.   this is *not* guaranteed to be the full path, but often just the
  1581.   same as `ParamStr (0)' which usually is the name given on the
  1582.   command line. Only on some systems with special support, it
  1583.   returns the full path when `ParamStr (0)' doesn't. }
  1584. function  ExecutablePath : TString; asmname '_p_executable_path';
  1585.  
  1586. { Returns a file name suitable for a global (system-wide) or local
  1587.   (user-specific) configuration file, depending on the Global
  1588.   parameter. The function does not guarantee that the file name
  1589.   returned exists or is readable or writable.
  1590.  
  1591.   In the following table, the base name `<base>' is given with the
  1592.   Name parameter. If it is empty, the base name is the name of the
  1593.   running program (as returned by ExecutablePath, without directory
  1594.   and extension. `<prefix>' (Unix only) stands for the value of the
  1595.   Prefix parameter (usual values include '', '/usr' and
  1596.   '/usr/local'). `<dir>' (Dos only) stands for the directory where
  1597.   the running program resides. `$foo' stands for the value of the
  1598.   environment variable `foo'.
  1599.  
  1600.          Global                    Local
  1601.   Unix:  <prefix>/etc/<base>.conf  $HOME/.<base>
  1602.  
  1603.   Dos:   $DJDIR\etc\<base>.ini     $HOME\<base>.cfg
  1604.          <dir>\<base>.ini          <dir>\<base>.cfg
  1605.  
  1606.   As you see, there are two possibilities under Dos. If the first
  1607.   file exists, it is returned. Otherwise, if the second file exists,
  1608.   that is returned. If none of them exists (but the program might
  1609.   want to create a file), if the environment variable (DJDIR or
  1610.   HOME, respectively) is set, the first file name is returned,
  1611.   otherwise the second one. This rather complicated scheme should
  1612.   give the most reasonable results for systems with or without DJGPP
  1613.   installed, and with or without already existing config files. Note
  1614.   that DJDIR is always set on systems with DJGPP installed, while
  1615.   HOME is not. However, it is easy for users to set it if they want
  1616.   their config files in a certain directory rather than with the
  1617.   executables. }
  1618. function  ConfigFileName (const Prefix, Name : String; Global : Boolean) : TString; asmname '_p_config_file_name';
  1619.  
  1620. { Returns a directory name suitable for global, machine-independent
  1621.   data. The function garantees that the name returned ends with a
  1622.   DirSeparator, but does not guarantee that it exists or is
  1623.   readable or writable.
  1624.  
  1625.   Note: If the prefix is empty, it is assumed to be '/usr'. (If you
  1626.   really want /share, you could pass '/' as the prefix, but that's
  1627.   very uncommon.)
  1628.  
  1629.   Unix: <prefix>/share/<base>/
  1630.  
  1631.   Dos:  $DJDIR\share\<base>\
  1632.         <dir>\
  1633.  
  1634.   About the symbols used above, and the two possibilities under Dos,
  1635.   see the comments for ConfigFileName. }
  1636. function  DataDirectoryName (const Prefix, Name : String) : TString; asmname '_p_data_directory_name';
  1637.  
  1638. { ==================== MATHEMATICAL ROUTINES ===================== }
  1639.  
  1640. function  IsInfinity   (x : Extended) : Boolean; attribute (const); asmname '_p_isinf';
  1641. function  IsNotANumber (x : Extended) : Boolean; attribute (const); asmname '_p_isnan';
  1642. procedure SplitReal    (x : Extended; var Exponent : Integer; var Mantissa : Extended); asmname '_p_frexp';
  1643. function  SinH         (x : Double)    : Double; asmname '_p_sinh';
  1644. function  CosH         (x : Double)    : Double; asmname '_p_cosh';
  1645. function  Arctan2      (y, x : Double) : Double; asmname '_p_arctan2';
  1646.  
  1647. type
  1648.   RandomSeedType = Cardinal (32);
  1649.   RandomizeType  = ^procedure;
  1650.   SeedRandomType = ^procedure (Seed : RandomSeedType);
  1651.   RandRealType   = ^function : LongestReal;
  1652.   RandIntType    = ^function (MaxValue : LongestCard) : LongestCard;
  1653.  
  1654. var
  1655.   RandomizePtr  : RandomizeType; asmname '_p_randomize_ptr'; external;
  1656.   SeedRandomPtr : SeedRandomType; asmname '_p_seedrandom_ptr'; external;
  1657.   RandRealPtr   : RandRealType; asmname '_p_randreal_ptr'; external;
  1658.   RandIntPtr    : RandIntType; asmname '_p_randint_ptr'; external;
  1659.  
  1660. procedure SeedRandom (Seed : RandomSeedType); asmname '_p_seedrandom';
  1661.  
  1662. end.
  1663.  
  1664. module GPC implementation;
  1665.  
  1666. {$ifndef HAVE_NO_RTS_CONFIG_H}
  1667. {$include "rts-config.inc"}
  1668. {$endif}
  1669. {$ifdef HAVE_LIBOS_HACKS}
  1670. {$L os-hacks}
  1671. {$endif}
  1672.  
  1673. end.
  1674.